﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Net;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using com.tiyma.components;
using com.tiyma.common;
using com.tiyma.model;


namespace com.tiyma.web
{

    public partial class Reader : BasePage
    {
        public long m_chapter_id = 0;
        public int m_site_id = 0;
        string m_site_name = string.Empty;
        public string m_chapter_name = string.Empty;
        public ChapterInfo m_chapter = null;
        public long m_user_id = 0;
        public string m_book_name = string.Empty;

        BookManager m_book_mgr = new BookManager();

        //获取章节内容的信息
        public string m_chapter_url = string.Empty;
        public string m_pic_url = string.Empty;



        protected void Page_Load(object sender, EventArgs e)
        {
            if (!long.TryParse(Request["chapterId"], out m_chapter_id))
                m_chapter_id = 0;

            if (!int.TryParse(Request["siteId"], out m_site_id))
                m_site_id = 0;

            BindChapter();

            if (Token != null)
            {
                m_user_id = Token.UserId;
            }
            m_book_name = m_chapter.BookName;
        }

        /// <summary>
        /// 绑定章节信息
        /// </summary>
        private void BindChapter()
        {

            SiteInfo t_site_info = null;

            m_chapter = m_book_mgr.GetChapterInfo(m_chapter_id, m_site_id, out t_site_info,Consts.ChapterType.reader);

            if (m_chapter == null )
            {
                RedirectDefaultPage();
                return;
            }

            CookieManager.SetCurReadBook(m_chapter);

            if (string.IsNullOrEmpty(m_chapter.BookName))
            {
                m_chapter.BookName = m_book_mgr.GetBookName(m_chapter.BookId);
            }

            if (t_site_info != null)
            {
                m_site_name = t_site_info.SiteName;
            }
            m_chapter_name = m_chapter.ChapterName;
            m_chapter_url = string.Format(Consts.ChapterPath, m_chapter.BookId, m_chapter.ChapterId);
            m_pic_url = string.Format(Consts.PicPath, m_chapter.BookId, m_chapter.ChapterId);

           
            if (m_chapter.IsDownLoad != Consts.ExistChapterContent && m_chapter.ChapterUrl.ToLower().IndexOf("vip")< 0)
            {
                string t_chapter_tip = string.Format("<center>本章节内容还没收录，页面正在努力搜索章节内容，您也可以<a href='{0}' target='_blank'>点击这里查看原始章节内容</a></center><br>", m_chapter.ChapterUrl);
                lblTip.Text = t_chapter_tip;
                lblscript.Text = string.Format("<script>SEONChapter('{0}');</script>", DESEncryptBYTriple.Encrypt(string.Format("{0}${1}${2}${3}${4}${5}",m_chapter.BookId, m_chapter.ChapterId,m_site_id,m_chapter.ChapterUrl,m_chapter.BookName,m_chapter.ChapterName)));

                return;

                //BookChapterManager t_chapter_mgr=new BookChapterManager();
                //string t_content = t_chapter_mgr.SearchNomalChapter(m_chapter,m_site_id);

                //if (!string.IsNullOrEmpty(t_content) && t_content.Length>300)
                //{
                //    string t_chapter_tip = string.Format("<center>本章节收录于互联网，如果您觉得章节有误，请<a href=\"javascript:SEOChapter('{1}');\">点击这里重新搜索章节内容</a>，或者<a href='{0}' target='_blank'>点击这里查看原始章节内容</a></center><br>", m_chapter.ChapterUrl, DESEncryptBYTriple.Encrypt(string.Format("{0}${1}${2}${3}", m_chapter.BookName, m_chapter.ChapterName, m_chapter.BookId, m_chapter.ChapterId)));

                //    lblTip.Text = t_chapter_tip;

                //    lblcontent.Text = t_content;

                //    return;
                //}
            }
        

            if (m_chapter.IsDownLoad != Consts.ExistChapterContent)
            {
                string t_chapter_tip = string.Format("<center>本章节内容还没收录，页面正在努力搜索章节内容，您也可以<a href='{0}' target='_blank'>点击这里查看原始章节内容</a></center><br>", m_chapter.ChapterUrl);
                lblTip.Text = t_chapter_tip;
                lblscript.Text =string.Format( "<script>SEOChapter('{0}');</script>",DESEncryptBYTriple.Encrypt(string.Format("{0}${1}${2}${3}", m_chapter.BookName, m_chapter.ChapterName,m_chapter.BookId,m_chapter.ChapterId)));

                m_chapter_name = m_chapter.ChapterName;
                return;
            }
 
            SetChapterCotnent();

        }

     

        /// <summary>
        /// 设置章节内容
        /// </summary>
        private void SetChapterCotnent()
        {
            string t_text = string.Empty;

            StringBuilder t_sb_img = new StringBuilder();

            try
            {
                using (StreamReader t_sm_read = new StreamReader(string.Format(AppConfig.ChapterPath, m_chapter.BookId, m_chapter.ChapterId), System.Text.Encoding.Default))
                {
                    t_text = t_sm_read.ReadToEnd();
                }

                if (!string.IsNullOrEmpty(t_text))
                {
                    Match t_mc = Regex.Match(t_text, "document.write\\(\\'(.*?)\\'\\)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                    if (t_mc != null && t_mc.Groups.Count > 0)
                        t_text = t_mc.Groups[1].Value.ToString();

                    if (SystemUtil.GetStringLength(t_text) < 600)
                    {
                        //如果是图片
                        //存在图片
                        MatchCollection t_ma = Regex.Matches(t_text, "<img[^<>]*?src=s*[\'\"]*([^\"\']*)[\'\"]*[^<>]*?>", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                        if (t_ma != null && t_ma.Count > 8)
                        {
                            t_text = Regex.Replace(t_text, "<img.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                            t_ma = null;
                        }

                        string t_last_img = string.Empty;

                        if (t_ma != null && t_ma.Count > 0)
                        {
                            foreach (Match t_mc_img in t_ma)
                            {
                                string t_img_url = t_mc_img.Groups[1].Value.ToString();

                                if (t_last_img == t_img_url)
                                    continue;


                                if (t_img_url.ToLower().IndexOf("book") > -1)
                                {
                                    m_pic_url = "http://www.89wx.com";
                                }

                                if (t_img_url.ToLower().IndexOf("http") < 0)
                                {
                                    t_img_url = string.Format("{0}{1}", m_pic_url, t_mc_img.Groups[1].Value.ToString());
                                }

                                t_sb_img.AppendFormat("<img src=\"{0}\" border=\"0\" /><br><br>", t_img_url);

                                t_last_img = t_img_url;
                            }
                        }
                    }
                    else
                    {
                        t_text = Regex.Replace(t_text, "<img[^<>]*?>", "", RegexOptions.IgnoreCase);
                    }
                }

                if (!string.IsNullOrEmpty(t_sb_img.ToString()))
                {
                    t_text = t_sb_img.ToString();
                }

                string t_chapter_tip = string.Format("<center>本章节收录于互联网，如果您觉得章节有误，请<a href=\"javascript:SEOChapter('{1}');\">点击这里重新搜索章节内容</a>，或者<a href='{0}' target='_blank'>点击这里查看原始章节内容</a></center><br>", m_chapter.ChapterUrl, DESEncryptBYTriple.Encrypt(string.Format("{0}${1}${2}${3}", m_chapter.BookName, m_chapter.ChapterName, m_chapter.BookId, m_chapter.ChapterId)));

                if (string.IsNullOrEmpty(t_text))
                {
                    t_chapter_tip = string.Format("<center>本章节内容还没收录，页面正在努力搜索章节内容，您也可以<a href='{0}' target='_blank'>点击这里查看原始章节内容</a></center><br>", m_chapter.ChapterUrl);
                    lblscript.Text = string.Format("<script>SEOChapter('{0}');</script>", DESEncryptBYTriple.Encrypt(string.Format("{0}${1}${2}${3}", m_chapter.BookName, m_chapter.ChapterName, m_chapter.BookId, m_chapter.ChapterId)));

                }

                lblTip.Text=t_chapter_tip ;

                lblcontent.Text = t_text;
            }
            catch (Exception ex)
            {
                LogHelper.Error("设置章节内容失败" + ex.ToString());
                string t_chapter_tip = string.Format("<center>本章节收录于互联网，如果您觉得章节有误，请<a href=\"javascript:SEOChapter('{1}');\">点击这里重新搜索章节内容</a>，或者<a href='{0}' target='_blank'>点击这里查看原始章节内容</a></center><br>", m_chapter.ChapterUrl, DESEncryptBYTriple.Encrypt(string.Format("{0}${1}${2}${3}", m_chapter.BookName, m_chapter.ChapterName, m_chapter.BookId, m_chapter.ChapterId)));
                lblTip.Text = t_chapter_tip;
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {

            Page.Title = string.Format("{0},{1},体验码小说网",m_chapter.BookName,m_chapter.ChapterName);
            string metaDescription =
                string.Format("{0}小说阅读,{0}最新章节,{1},最新更新尽在体验码小说网",
                m_chapter.BookName,
                (m_chapter.ChapterName != null && m_chapter.ChapterName != "" ? (m_chapter.ChapterName.Trim().Length >= 60 ? m_chapter.ChapterName.Trim().Substring(0, 60).Replace("\"", "'").Replace("<br>", "").Replace("＜p＞", "").Replace("<p>", "").Replace("<", "＜").Replace(">", "＞").Replace("　　", " ") + "..." : m_chapter.ChapterName.Trim().Replace("\"", "'")) : ""));

            mataKeywords.Content = m_chapter.BookName  + "," + m_chapter.ChapterName + ",最新章节,最新更新," + ",体验码小说网";
            mataDescription.Content = metaDescription;


        }
       
    }
}
